MIN & MAX

The MAX and MIN are used to retrieve the maximum and minimum values from a column which value can be numerical, character string, or dates. For numerical values, the highest number is returned as the maximum, and the lowest number is returned as the minimum. When dealing with string characters, the closest value starting from 'A' is returned as the minimum, and the closest value starting from 'Z' is returned as the maximum.

For Example:

Let's find out the highest and lowest of the salary column from the table employees.

max

select max(salary) from employees;

Result:

The highest salary is 24000.

To find the highest value in string characters:

select max(first_name) from employees;

Result:

As observed, MAX returns the value with the starting letter closest to Z, which is V.

min

select min(salary) from employees;

Result:

So the lowest salary is 2500.

To find the lowest value in string characters:

select min(first_name) from employees;

Result:

As observed, MIN returns the value with the starting letter closest to A.

Ecto for max & min

max/1

The max/1 function is used to find the maximum value of a specific field in a schema.

Expressions

For Example:

HR.Employee
|> select([c], max(c.salary))
|> HR.Repo.all()

Here, c is the reference variable referring to HR.Employee. Refer Aliases in Ecto to understand aliases/reference variables.

Result:

iex(60)> HR.Employee |> select([c], max(c.salary)) |> HR.Repo.all()
[Decimal.new("24000.00")]

The maximum value of the salary field is 24000.

Keywords

HR.Repo.all(from c in HR.Employee, select: max(c.salary))

min/1

The min/1 function is used to find the lowest value of a specific field in a schema

Expressions

For Example:

HR.Employee
|> select([c], min(c.salary))
|> HR.Repo.all()

Result:

iex(62)> HR.Employee |> select([c], min(c.salary)) |> HR.Repo.all()
[Decimal.new("2500.00")]

The minimum value in the salary field is 2500.

Keywords

HR.Repo.all(from c in HR.Employee, select: min(c.salary))

select: is a key. c is a value that is a reference variable for HR.Employee.